<template>
  <div class="container">
    <div class="search-box">
      <span>档案名称:</span>
      <el-input
        v-model="searchForm.archTitle"
        placeholder="请输入搜索的档案名称"
        style="width: 200px"
        class="margin-left-m"
        size="small"
      />
      <el-button
        class="margin-left-m"
        type="primary"
        size="small"
        @click="getTableList()"
      >检索</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%; margin-top: 10px">
      <el-table-column prop="archMainCode" label="档案编号" align="center" />
      <el-table-column prop="archTitle" label="档案名称" align="center" />
      <el-table-column prop="notes" label="备注" align="center" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            plain
            @click="handleRead(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            plain
            @click="handleLabel(scope.row)"
          >打标</el-button>
          <!-- <el-button
            size="mini"
            type="danger"
            plain
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :current-page.sync="searchForm.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="searchForm.pageSize"
        layout="sizes, total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="打标" :visible.sync="labelVisible" width="90%">
      <div class="label-box">
        <div style="width: 50%">
          <div class="label-detail-box">
            档案编号: {{ labelItem.archMainCode }}
          </div>
          <div class="label-detail-box">档案标题:</div>
          <div
            id="labelContent"
            class="label-content"
            @mouseup.stop="highlight($event)"
            v-html="labelItem.lblContent"
          />
          <div class="label-detail-box">备注: {{ labelItem.notes }}</div>
        </div>
        <div class="right-label-box">
          <el-table :data="labelList">
            <el-table-column prop="labelName" label="标签">
              <template slot-scope="scope">
                <div class="label-name-box">
                  <div
                    class="label-name-color-box"
                    :style="{ 'background-color': scope.row.labelColor }"
                  />
                  <div>
                    {{ scope.row.labelName }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="lblContent" label="标注内容" width="200">
              <template slot-scope="scope">
                <div class="lbl-content-box" :title="scope.row.lblContent">
                  {{ scope.row.lblContent }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createtime" label="打标时间" />
            <el-table-column prop="" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="small"
                  plain
                  @click="deleteLabel(scope.row.archLblDtlId)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :current-page.sync="labelTable.pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="labelTable.pageSize"
            layout="sizes, total, prev, pager, next"
            :total="labelTotal"
            @size-change="handleLabelSizeChange"
            @current-change="handleLabelCurrentChange"
          />
        </div>
      </div>
      <div slot="footer">
        <el-button size="small" @click="labelVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="人工打标" :visible.sync="labelDialog" width="30%">
      <el-form
        ref="labelInsertForm"
        :model="labelInsertForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="知识类别" prop="knowCateId">
          <el-cascader
            v-model="labelInsertForm.knowCateId"
            style="width: 100%"
            :options="highlightOptions"
            placeholder="请选择知识类别"
            :props="{ checkStrictly: true }"
            clearable
            @change="handleSelectChange"
          />
        </el-form-item>
        <el-form-item label="标签类型" prop="labelCateId">
          <el-select
            v-model="labelInsertForm.labelCateId"
            placeholder="请选择标签"
            style="width: 100%"
            @change="handleLabelOption"
          >
            <el-option
              v-for="(item, index) in labelOptions"
              :key="index"
              :label="item.labelName"
              :value="item.labelCateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签颜色" prop="labelColor">
          <div :style="{ background: color }" class="label-color-box" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="labelDialog = false">取 消</el-button>
        <el-button type="primary" @click="labelSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="详情" :visible.sync="readDialogVisible" width="70%">
      <div class="detail-box">
        <div>
          档案编号:
          <span class="right-content">{{ labelDetailItem.archMainCode }}</span>
        </div>
        <div class="detail-content-box">
          <div class="detail-content-left">档案标题:</div>
          <div v-if="labelDetailItem.list.total > 0" class="lbl-content">
            <div
              class="detail-content-right detail-left"
              v-html="labelDetailItem.item.lblContent"
            />
            <div class="detail-label-box">
              <div
                v-for="(label, labelIndex) in labelDetailItem.list.records"
                :key="labelIndex"
                :style="{ border: '1px solid' + label.labelColor }"
                class="detail-label-item-box"
                @click="clickLabel(label)"
              >
                <div class="label-top-box">
                  <div
                    class="label-color-box"
                    :style="{ background: label.labelColor }"
                  />
                  <div>
                    {{ label.labelName }}
                  </div>
                </div>
                <div class="detail-label-content" :title="label.lblContent">
                  {{ label.lblContent }}
                </div>
              </div>
            </div>
          </div>
          <div
            v-else
            class="detail-content-right"
            v-html="labelDetailItem.item.lblContent"
          />
        </div>
        <div>
          备注:
          <span class="right-content">{{
            labelDetailItem.notes ? labelDetailItem.notes : "暂无备注"
          }}</span>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="readDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllArchLabelMain, getArchLabelDetails, updateKnowAPI, deleteByarchLblDtlId, getSingleLabelMain, insertArchLabelDetail, getCategoryAllLevels, getLabelsByKnowCateId, updateArchLabelMain } from '@/api/knowMan'
export default {
  data() {
    return {
      tableData: [],
      searchForm: {
        knowTitle: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      labelVisible: false,
      content: '',
      labelData: [],
      labelDialog: false,
      labelInsertForm: {},
      rules: {
        archTitle: [
          { required: true, message: '请输入知识标题', trigger: 'blur' }
        ],
        knowContent: [
          { required: true, message: '请输入知识内容', trigger: 'blur' }
        ],
        knowCateId: [
          { required: true, message: '请选择知识类别', trigger: 'change' }
        ],
        labelCateId: [
          { required: true, message: '请选择标签类型', trigger: 'change' }
        ]
      },
      highlightOptions: [],
      labelOptions: [],
      color: '',
      labelItem: {},
      labelDetailItem: {
        list: {
          total: 0
        },
        item: {
          lblContent: ''
        }
      },
      labelList: [],
      knowCateId: '',
      labelTable: {
        pageNum: 1,
        pageSize: 10
      },
      labelTotal: 0,
      readDialogVisible: false
    }
  },
  created() {
    this.getTableList()
    this.getCategoryAllLevels()
  },
  methods: {
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getTableList()
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.getTableList()
    },
    handleLabelSizeChange(val) {
      this.labelTable.pageSize = val
      this.queryTable()
    },
    handleLabelCurrentChange(val) {
      this.labelTable.pageNum = val
      this.queryTable()
    },
    // 获取数据列表
    getTableList() {
      getAllArchLabelMain(this.searchForm).then((res) => {
        this.tableData = res.list.records
        this.total = res.list.total
      })
    },
    // 获取所有知识类别
    getCategoryAllLevels() {
      getCategoryAllLevels().then((res) => {
        this.highlightOptions = res.list
      })
    },
    // 点击详情
    handleRead(row) {
      getSingleLabelMain({
        archLblId: row.archLblId
      }).then((res) => {
        console.log(res)
        this.readDialogVisible = true
        this.labelDetailItem = { ...res }
      }).catch((err) => {
        console.log(err)
      })
      // this.getFilesByKnowId(row.knowId)
    },
    // 点击选择打标签的知识分类选择
    handleSelectChange(val) {
      this.knowCateId = val[val.length - 1]
      console.log(this.knowCateId)
      getLabelsByKnowCateId({
        knowCateId: val[val.length - 1]
      }).then((res) => {
        this.labelOptions = res.item.list
      })
      this.$forceUpdate()
    },
    // 点击打标
    handleLabel(row) {
      this.labelItem = { ...row }
      this.queryTable()
      this.labelInsertForm.archLblId = row.archLblId
      // getCategorySingleLevels({
      //   knowCateId: row.knowCateId
      // }).then((res) => {
      //   this.highlightOptions = res.list
      //   console.log(this.highlightOptions)
      // })
      // getArchLabelsByKnowCateId(param).then((res) => {
      //   this.labelOptions = res.item.list
      // }).catch((err) => {
      //   console.log(err)
      // })
      this.labelVisible = true
    },
    // 点击打标完成
    handleFinishLabel(row) {
      this.$confirm('该知识将进入审核阶段，确定打标完成吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          updateKnowAPI({
            knowId: row.knowId,
            knowState: 5
          }).then((res) => {
            this.$message.success('打标完成')
            this.getAllKnowList()
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取右边标签表格数据
    queryTable() {
      getArchLabelDetails({
        archLblId: this.labelItem.archLblId
      }).then((res) => {
        this.labelList = res.list.records
        this.labelTotal = res.list.total
      })
    },
    // 选中标注文本
    highlight(e) {
      if (window.getSelection().toString() === '') {
        return
      }
      this.labelDialog = true
      this.selectedContent = window.getSelection()
      this.labelInsertForm.lblContent = window.getSelection().toString()
      this.range = window.getSelection().getRangeAt(0)
    },
    // 点击打标签的确定
    labelSubmit() {
      this.$refs['labelInsertForm'].validate((valid) => {
        if (valid) {
          insertArchLabelDetail({
            archLblId: this.labelInsertForm.archLblId,
            lblContent: this.labelInsertForm.lblContent,
            labelCateId: this.labelInsertForm.labelCateId
          }).then(res => {
            this.labelDialog = false
            try {
              const span = document.createElement('span')
              span.className = 'highlight'
              const delicon = document.createElement('i')
              delicon.setAttribute('id', res.archLblDtlId)
              this.range.surroundContents(span)// 把指定节点插入选区的起始位置，然后把指定节点的内容替换为选区的内容。
              const color = this.color
              span.innerHTML = `<em style="background:${color};color:white;margin:0 5px;padding:0 5px;font-style: normal;">${span.innerHTML}`
              span.lastChild.appendChild(delicon)
              window.getSelection().removeAllRanges()
            } catch (e) {
              console.log(e)
            }
            const content = document.getElementById('labelContent').innerHTML
            updateArchLabelMain({
              archLblId: this.labelInsertForm.archLblId,
              lblContent: content
            }).catch((error) => {
              this.$message.error(error.toString())
            })
            this.queryTable()

            this.selectedContent = null
            this.range = null
            this.showDetail = false
            this.$message.success('打标成功')
            this.labelInsertForm = {
              archLblId: '',
              knowCateId: this.knowCateId,
              labelCateId: '',
              lblContent: ''
            }
          }).catch((error) => {
            this.$message.error(error.toString())
          })
        }
      })
    },
    // 点击选择知识标签
    handleLabelOption(val) {
      this.labelOptions.find((item) => {
        if (item.labelCateId === val) { this.color = item.labelColor }
        return
      })
    },
    // 删除右边标签
    deleteLabel(id) {
      console.log(this.labelInsertForm, id)
      this.$confirm('你确定要删除吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          try {
            const annotateContent =
              document.getElementById(id).parentNode.parentNode.parentNode
            const span = document.getElementById(id).parentNode.parentNode
            const button = document.getElementById(id).parentNode
            let emtext = ''
            if (span.firstChild.getElementsByTagName('span').length > 0) {
              const kk = span.firstChild.innerHTML
              const newSpan = document.createElement('span')
              newSpan.className = 'tagReplace'
              span.removeChild(button)
              annotateContent.insertBefore(newSpan, span)
              annotateContent.removeChild(span)
              annotateContent.innerHTML = annotateContent.innerHTML.replace('<span class="tagReplace"></span>', kk)
            } else {
              emtext = span.firstChild.innerText.trim()
              span.removeChild(button)
              const textNode = document.createTextNode(emtext)
              annotateContent.insertBefore(textNode, span)
              annotateContent.removeChild(span)
            }
            window.getSelection().removeAllRanges()
          } catch (e) {
            console.log(e)
          }
          const content = document.getElementById('labelContent').innerHTML
          this.labelItem.lblContent = content
          updateArchLabelMain({
            archLblId: this.labelInsertForm.archLblId,
            lblContent: content
          }).then(res => {
          }).catch((error) => {
            this.$message.error(error.toString())
          })
          deleteByarchLblDtlId({
            archLblDtlId: id
          }).then((res) => {
            this.$message.success('删除成功')
            this.queryTable()
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 15px;
}
.search-box {
  display: flex;
  align-items: center;
  color: rgb(96, 98, 102);
  font-size: 15px;
}
.margin-left-m {
  margin-left: 10px;
}
.pagination {
  width: auto;
  display: flex;
  margin-top: 10px;
  align-items: center;
}

.label-box {
  display: flex;
  justify-content: center;
}
.label-content {
  width: 100%;
  border-radius: 6px;
  border: 1px solid #eee;
  padding: 10px;
  margin-top: 10px;
  line-height: 25px;
  font-size: 15px;
  text-indent: 30px;
  white-space: pre-line;
}
#labelContent::before {
  content: "\00a0\00a0";
}
.label-color-box {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  border: 1px solid #eee;
  margin-top: 3px;
}
.right-label-box {
  width: 49%;
  margin-left: 1%;
  padding: 10px;
}
.lbl-content-box {
  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 2;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
.label-name-box {
  display: flex;
  align-items: center;
}
.label-name-color-box {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #eee;
  margin-right: 3px;
}
.detail-box {
  font-size: 16px;
  line-height: 30px;
}
.right-content {
  margin-left: 8px;
}
.detail-content-box {
  display: flex;
}
.detail-content-left {
  width: auto;
  white-space: nowrap;
  margin-right: 10px;
}
.detail-content-right {
  border: 1px solid #eee;
  border-radius: 10px;
  padding: 7px 10px;
}
.lbl-content {
  display: flex;
}
.detail-left {
  flex: 3;
}
.detail-label-box {
  flex: 1;
  min-width: 200px;
}
.detail-label-item-box {
  padding: 5px 10px;
  border-radius: 10px;
  margin-bottom: 4px;
  margin-left: 10px;
}
.label-top-box {
  display: flex;
  align-items: center;
}
.label-color-box {
  width: 20px;
  height: 20px;
  border-radius: 10px;
  margin-right: 10px;
}
.detail-label-content {
  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 2;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  font-size: 13px;
  line-height: 26px;
}

.file-box {
  display: flex;
  align-items: center;
}
.download-file {
  color: #409eff;
  cursor: pointer;
}
.label-detail-box {
  font-size: 18px;
  font-weight: bold;
  height: 30px;
  line-height: 30px;
}
</style>
